//
//  FaceManager.swift
//  MM2
//
//  Created by 李成明 on 2022/1/3.
//

import Foundation
import SwiftyJSON
import Moya

class FaceManager {
    
    static let share = FaceManager()
    
    func faceDetect(image: UIImage, detectComplete:((Int) -> Void)? = nil, complete:((FaceUseResultModel?) -> Void)? = nil) {
//        detcctByUrl(image: image, detectComplete: detectComplete, complete: complete)
        detectByString(image: image, detectComplete: detectComplete, complete: complete)
    }
    
    func faceAnalyze(faceToken: String, complete:((FaceUseResultModel?) -> Void)? = nil, img: UIImage) {
        MoyaNetwork.request(target: BaseApi.faceAnalyze(face_tokens: faceToken)) { json, jsonStr in
            guard let model = FaceAnalyzeModel.deserialize(from: jsonStr) else {
                complete?(nil)
                return
            }
            let useModel = FaceUseResultModel.init(model: model)
            self.uploadResult(model: useModel, img: img)
            complete?(useModel)
        } error: { intI, str in
            print("--->inti\(intI)--->sdstr\(str)")
        } failure: { error in
            print("\(error)")
        }
    }
}


extension FaceManager {
    private func detectByfile(image: UIImage, detectComplete:((Int) -> Void)? = nil, complete:((FaceUseResultModel?) -> Void)? = nil) {
        guard let data = image.pngData() else { return }
        
        MoyaNetwork.request(target: BaseApi.faceDetectFile(image_file: data)) { json, jsonStr in
            guard let model = FaceResultModel.deserialize(from:jsonStr) else { return }
            print("\n\n\n\(jsonStr)")
            detectComplete?(model.face_num)
            guard let face = model.faces.first, let faceToken = face.face_token else {
                complete?(nil)
                return
            }
            self.faceAnalyze(faceToken: faceToken, complete: complete, img: image)
        }
    }
    
    private func detectByString(image: UIImage, detectComplete:((Int) -> Void)? = nil, complete:((FaceUseResultModel?) -> Void)? = nil) {
        guard let data = Util.compressImageData(img: image) else { return }
        let encodedImageStr = data.base64EncodedString()

        MoyaNetwork.request(target: BaseApi.faceDetect(image_base64: encodedImageStr)) { json, jsonStr in
            guard let model = FaceResultModel.deserialize(from:jsonStr) else { return }

            print("\n\n\n\(jsonStr)")
            detectComplete?(model.face_num)
            guard let face = model.faces.first, let faceToken = face.face_token else {
                complete?(nil)
                return
            }
            self.faceAnalyze(faceToken: faceToken, complete: complete, img: image)
        }
    }
    
    private func detcctByUrl(image: UIImage, detectComplete:((Int) -> Void)? = nil, complete:((FaceUseResultModel?) -> Void)? = nil) {
        guard let ossData = Util.compressImageData(img: image) else { return }
        OSSManager.share.uploadSingleImg(data: ossData, path: "image/\(User.share.userId)/\(Util.randomString())") { imgUrl in
            MoyaNetwork.request(target: BaseApi.faceDetectUrl(image_url: imgUrl)) { json, jsonStr in
                guard let model = FaceResultModel.deserialize(from:jsonStr) else { return }

                print("\n\n\n\(jsonStr)")
                detectComplete?(model.face_num)
                guard let face = model.faces.first, let faceToken = face.face_token else {
                    complete?(nil)
                    return
                }
                self.faceAnalyze(faceToken: faceToken, complete: complete, img: image)
            }
        }
    }
    
    private func uploadResult(model: FaceUseResultModel, img: UIImage) {
        let objectId = "image/\(User.share.userId)/\(Util.randomString())"
        MoyaNetwork.request(target: BaseApi.uploadFaceResult(model: model, imageUrl: (ossBaseUrl + objectId), objectId: objectId)) { json, jsonStr in
            if json["data"]["isTop"].boolValue, let imageData = Util.compressImageData(img: img) {
                OSSManager.share.uploadSingleImg(data: imageData, path: objectId, completion: nil)
            }
        }
    }
}
